const cheerio = require("cheerio");
const http = require("http");
const fs = require("fs");
const path = require("path");

http.get("http://192.168.42.166:3000/data" , (res) => {
    let str = "";    
    res.on("data" , (chunk) => {
        str += chunk;
    })
    res.on("end" , () => {
        // console.log(str);
        let $ = cheerio.load(str);
        let arr = [];
        // console.log($(".channel-detail").length);
        console.log($(".channel-detail-orange").length);
        let length = $(".channel-detail-orange").length;
        for(let i = 0 ; i < length ; i++) {
            console.log($(".channel-detail-orange").eq(i).children().eq(0).html());
            let length = arr.length;
            arr[length] = {};
            if($(".channel-detail-orange").eq(i).children().eq(0).html()) {
                arr[length].movieOrange = $(".channel-detail-orange").eq(i).children().eq(0).html() + $(".channel-detail-orange").eq(i).children().eq(1).html();
                i++;
            } else {
                arr[length].movieOrange = "暂无评分"
            }
            // console.log($(".channel-detail-orange").eq(i).children().eq(1).html());
        }
        console.log($(".movie-item-title a").length);
        for(let j = 0 ; j < $(".movie-item-title a").length ; j++) {
            // console.log($(".movie-item-title a").eq(j).text());
            // console.log($(".movie-item-title a").eq(j).attr("data-val").slice(1,-1).split(':')[1]);
            arr[j].movieId = $(".movie-item-title a").eq(j).attr("data-val").slice(1,-1).split(':')[1];
            arr[j].movieName = $(".movie-item-title a").eq(j).text();
        }
        console.log(arr);
        console.log(arr.length);
        fs.writeFileSync(path.join(__dirname , "data.json") , JSON.stringify(arr , null , 2));
    })  
})